//Page Object
const { request, uploadFile2, wxLogin} = require('../../utils/request')
Page({
  data: {
    nickNameDialogVisible: false,
    nick: '',
    wechatAvatar:'',
    userInfo:{}
  },
  //options(Object)
  onLoad: function(options){
    this.initUserInfo()
  },
 
  onShow: function(){
    
  },
  jumpArticle(event:any){
    let id = event.currentTarget.dataset.id
    wx.navigateTo({
      url:'/pages/article/article?id='+id
    })
  },
  async bindchooseavatar(e:any){
    let avatarUrl =  e.detail.avatarUrl
    let imgUrl = await uploadFile2(avatarUrl)
    request({
      url: '/users/personal-info',
      method: 'POST',
      data: {
        avatar: imgUrl
      },
      success:()=>{
        this.setData({
          wechatAvatar: imgUrl
        })
        this.data.userInfo.wechatAvatar = imgUrl
        wx.setStorageSync('userInfo', this.data.userInfo)
      }
    })
  },
  showNickNameDialog(){
    this.setData({
      nickNameDialogVisible: true
    })
  },
  hideNickNameDialog(){
    this.setData({
      nickNameDialogVisible: false
    })
  },
  initUserInfo(){
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo:userInfo,
      wechatAvatar:userInfo.wechatAvatar,
      nick:userInfo.nick
    })
  },
  updateNickName(){
    this.showNickNameDialog()
  },
  bindNickNameInput(event: any){
    const nick = event.detail.value
    this.setData({
      nick
    })
  },
  confirmNickName(){
    const {nick} = this.data
    if(nick){
      if(nick.length > 10){
        wx.showToast({
          title: '昵称不能超过10个字符',
          icon: 'none'
        })
        return 
      }
      request({
        url: '/users/personal-info',
        method: 'POST',
        data: {
          nick
        },
        success:()=>{
          this.setData({
            nickNameDialogVisible: false
          })
          this.data.userInfo.nick = nick
          this.setData({
            userInfo:this.data.userInfo
          })
          wx.setStorageSync('userInfo', this.data.userInfo)
        }
      })
    }else {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
    }
  },
  cancelNickName(){
    this.setData({
      nickName: this.data.userInfo.nickName
    })
  }
});